﻿using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace MS.BasicData.Infrastructure
{
    public class BaseRepository<T> : IBaseRepository<T> where T : class
    {
        private readonly UserDataDbconterxt _db;

        private readonly ILogger<BaseRepository<T>> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="db"></param>
        /// <param name="logger"></param>
        public BaseRepository(UserDataDbconterxt db, ILogger<BaseRepository<T>> logger)
        {
            _db = db;
            _logger = logger;
        }

        public async Task<T?> GetAll(Expression<Func<T, bool>> where)
        {
            return await _db.Set<T>().FirstOrDefaultAsync(where);
        }

        public async Task<IList<T>> GetAllAsync(Expression<Func<T, bool>> where)
        {
            return await _db.Set<T>().Where(where).ToListAsync();
        }

        public async Task<IList<T>> GetAllAsync()
        {
            return await _db.Set<T>().ToListAsync();
        }

        public async Task<int> InsertAsync(T entity)
        {
            await _db.Set<T>().AddAsync(entity);
            return await _db.SaveChangesAsync();
        }
        

        public async Task<int> UpdateAsync(T entity)
        {
             _db.Set<T>().Update(entity);
            return await _db.SaveChangesAsync();
        }
    }
}
